"use strict";
var Locale = require("element-ui/lib/mixins/locale");
var AMapLoader = require("@amap/amap-jsapi-loader");
var EleModal = require("../ele-modal");
var license = require("../utils/license");
function _interopDefaultLegacy(e) {
  return e && typeof e === "object" && "default" in e ? e : { "default": e };
}
var Locale__default = /* @__PURE__ */ _interopDefaultLegacy(Locale);
var AMapLoader__default = /* @__PURE__ */ _interopDefaultLegacy(AMapLoader);
var EleModal__default = /* @__PURE__ */ _interopDefaultLegacy(EleModal);
var render = function() {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c("ele-modal", { attrs: { "visible": _vm.show, "title": _vm.title || _vm.t("ele.map.title"), "width": _vm.width, "show-close": _vm.showClose, "custom-class": _vm.dialogClass, "close-on-click-modal": _vm.closeOnClickModal, "close-on-press-escape": _vm.closeOnPressEscape, "destroy-on-close": _vm.destroyOnClose, "lock-scroll": _vm.lockScroll, "append-to-body": _vm.appendToBody, "modal-append-to-body": _vm.modalAppendToBody, "modal": _vm.modal, "top": _vm.top, "movable": _vm.movable, "move-out": _vm.moveOut, "move-out-positive": _vm.moveOutPositive, "resizable": _vm.resizable, "maxable": _vm.maxable, "multiple": _vm.multiple, "fullscreen": _vm.fullscreen, "inner": _vm.inner, "reset-on-close": _vm.resetOnClose, "centered": _vm.centered, "mask-keep-alive": false }, on: { "open": _vm.onOpen, "closed": _vm.onClosed, "update:visible": _vm.updateVisible } }, [_c("div", { directives: [{ name: "loading", rawName: "v-loading", value: _vm.loading, expression: "loading" }] }, [_c("div", { staticClass: "ele-map-picker-header" }, [_c("div", { staticClass: "ele-map-picker-header-search" }, [_c("el-autocomplete", { attrs: { "fetch-suggestions": _vm.onSearch, "placeholder": _vm.searchPlaceholder || _vm.t("ele.map.placeholder"), "popper-class": _vm.searchPopClass }, on: { "select": _vm.onSelect, "blur": _vm.onSuggestionBlur }, scopedSlots: _vm._u([{ key: "default", fn: function(ref) {
    var item = ref.item;
    return [_c("div", { staticClass: "ele-map-picker-poi-item ele-map-picker-suggestion-item" }, [_c("i", { staticClass: "ele-map-picker-poi-item-icon el-icon-search" }), _c("div", { staticClass: "ele-map-picker-poi-item-title" }, [_vm._v(_vm._s(item.name))]), item.address ? _c("div", { staticClass: "ele-map-picker-poi-item-address" }, [_vm._v(" " + _vm._s(item.address) + " ")]) : _vm._e()])];
  } }]), model: { value: _vm.suggestionKeywords, callback: function($$v) {
    _vm.suggestionKeywords = $$v;
  }, expression: "suggestionKeywords" } }, [_c("i", { staticClass: "el-icon-search el-input__icon", attrs: { "slot": "suffix" }, slot: "suffix" })])], 1), _c("el-button", { staticClass: "ele-btn-icon", attrs: { "type": "primary", "icon": "el-icon-check", "loading": _vm.doneLoading }, on: { "click": _vm.onDone } }, [_vm._v(" " + _vm._s(_vm.okText || _vm.t("ele.map.ok")) + " ")])], 1), _c("div", { staticClass: "ele-map-picker-body" }, [_c("div", { staticClass: "ele-map-picker-main" }, [_c("div", { ref: "mapEl", style: { height: _vm.height } }), _vm.searchType === 0 ? [_c("i", { staticClass: "ele-map-picker-main-plus el-icon-plus" }), _c("img", { class: _vm.iconClass, attrs: { "src": _vm.markerSrc, "alt": "" } })] : _vm._e()], 2), _c("div", { directives: [{ name: "loading", rawName: "v-loading", value: _vm.poiLoading, expression: "poiLoading" }], staticClass: "ele-map-picker-poi-list", style: { height: _vm.height } }, _vm._l(_vm.poiData, function(poi, index2) {
    return _c("div", { key: index2, class: ["ele-map-picker-poi-item", { active: poi.selected }], on: { "click": function($event) {
      return _vm.onChoose(index2);
    } } }, [_c("i", { staticClass: "ele-map-picker-poi-item-icon el-icon-location-outline" }), _c("div", { staticClass: "ele-map-picker-poi-item-title" }, [_vm._v(_vm._s(poi.name))]), poi.address ? _c("div", { staticClass: "ele-map-picker-poi-item-address" }, [_vm._v(" " + _vm._s(poi.address) + " ")]) : _vm._e(), _c("i", { staticClass: "el-icon-circle-check ele-map-picker-poi-item-check" })]);
  }), 0)])])]);
};
var staticRenderFns = [];
function normalizeComponent(scriptExports, render2, staticRenderFns2, functionalTemplate, injectStyles, scopeId, moduleIdentifier, shadowMode) {
  var options = typeof scriptExports === "function" ? scriptExports.options : scriptExports;
  if (render2) {
    options.render = render2;
    options.staticRenderFns = staticRenderFns2;
    options._compiled = true;
  }
  if (functionalTemplate) {
    options.functional = true;
  }
  if (scopeId) {
    options._scopeId = "data-v-" + scopeId;
  }
  var hook;
  if (moduleIdentifier) {
    hook = function(context) {
      context = context || this.$vnode && this.$vnode.ssrContext || this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext;
      if (!context && typeof __VUE_SSR_CONTEXT__ !== "undefined") {
        context = __VUE_SSR_CONTEXT__;
      }
      if (injectStyles) {
        injectStyles.call(this, context);
      }
      if (context && context._registeredComponents) {
        context._registeredComponents.add(moduleIdentifier);
      }
    };
    options._ssrRegister = hook;
  } else if (injectStyles) {
    hook = shadowMode ? function() {
      injectStyles.call(this, (options.functional ? this.parent : this).$root.$options.shadowRoot);
    } : injectStyles;
  }
  if (hook) {
    if (options.functional) {
      options._injectStyles = hook;
      var originalRender = options.render;
      options.render = function renderWithStyleInjection(h, context) {
        hook.call(context);
        return originalRender(h, context);
      };
    } else {
      var existing = options.beforeCreate;
      options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
    }
  }
  return {
    exports: scriptExports,
    options
  };
}
const __vue2_script = {
  name: "EleMapPicker",
  components: { EleModal: EleModal__default["default"] },
  mixins: [Locale__default["default"]],
  props: {
    show: Boolean,
    height: {
      type: String,
      default: "450px"
    },
    center: Array,
    zoom: {
      type: Number,
      default: 11
    },
    chooseZoom: {
      type: Number,
      default: 17
    },
    poiSize: {
      type: Number,
      default: 30
    },
    poiType: {
      type: String,
      default: ""
    },
    poiKeywords: {
      type: String,
      default: ""
    },
    poiRadius: {
      type: Number,
      default: 1e3
    },
    needCity: Boolean,
    forceChoose: {
      type: Boolean,
      default: true
    },
    suggestionCity: {
      type: String,
      default: "\u5168\u56FD"
    },
    searchType: {
      type: Number,
      default: 0,
      validator: (value) => {
        return [0, 1].includes(value);
      }
    },
    searchPlaceholder: String,
    markerSrc: {
      type: String,
      default: "https://3gimg.qq.com/lightmap/components/locationPicker2/image/marker.png"
    },
    mapKey: String,
    mapVersion: {
      type: String,
      default: "2.0"
    },
    mapStyle: String,
    title: String,
    width: {
      type: String,
      default: "780px"
    },
    customClass: String,
    closeOnClickModal: {
      type: Boolean,
      default: true
    },
    closeOnPressEscape: {
      type: Boolean,
      default: true
    },
    showClose: {
      type: Boolean,
      default: true
    },
    lockScroll: {
      type: Boolean,
      default: true
    },
    appendToBody: Boolean,
    modalAppendToBody: {
      type: Boolean,
      default: true
    },
    modal: {
      type: Boolean,
      default: true
    },
    top: String,
    destroyOnClose: {
      type: Boolean,
      default: false
    },
    movable: {
      type: Boolean,
      default: true
    },
    moveOut: Boolean,
    moveOutPositive: Boolean,
    resizable: [Boolean, String],
    maxable: Boolean,
    multiple: Boolean,
    fullscreen: Boolean,
    inner: Boolean,
    resetOnClose: {
      type: Boolean,
      default: true
    },
    centered: Boolean,
    okText: String,
    darkMode: Boolean
  },
  emits: ["done", "open", "closed", "update:show"],
  data() {
    return {
      authenticated: license.checkLicense(),
      poiData: [],
      suggestionData: [],
      suggestionKeywords: "",
      loading: true,
      poiLoading: false,
      doneLoading: false,
      iconClass: ["ele-map-picker-main-icon"],
      lastSuggestion: "",
      chooseSuggestion: null,
      isSelMove: false,
      map: null,
      placeSearch: null,
      autoComplete: null,
      centerMarker: null
    };
  },
  computed: {
    dialogClass() {
      const classes = ["ele-map-picker-dialog"];
      if (this.customClass !== 0) {
        classes.push(this.customClass);
      }
      return classes.join(" ");
    },
    searchPopClass() {
      const classes = ["ele-map-picker-search-pop"];
      if (this.searchType !== 0) {
        classes.push("ele-map-picker-hide");
      }
      return classes.join(" ");
    }
  },
  methods: {
    onOpen() {
      this.renderMap();
      this.$emit("open");
    },
    onClosed() {
      if (this.destroyOnClose) {
        this.destroyAll();
      }
      this.$emit("closed");
    },
    updateVisible(value) {
      this.$emit("update:show", value);
    },
    onChoose(index2) {
      this.isSelMove = true;
      this.setPoiSelected(index2);
      const { lng, lat } = this.poiData[index2].location;
      this.setMapCenter(lng, lat, this.chooseZoom);
      if (this.searchType !== 0) {
        this.showCenterMarker(lng, lat);
      } else {
        this.bounceIcon();
      }
    },
    onSearch(value, callback) {
      if (!value || this.lastSuggestion === value) {
        callback(this.suggestionData);
        return;
      }
      this.lastSuggestion = value;
      if (this.searchType !== 0) {
        this.poiLoading = true;
      }
      this.searchKeywords(value).then((data) => {
        if (this.searchType === 0) {
          this.suggestionData = data;
          callback(this.suggestionData);
        } else {
          this.poiData = data;
          this.poiLoading = false;
          this.removeCenterMarker();
          callback([]);
        }
      }).catch((e) => {
        this.poiLoading = false;
        console.error(e);
      });
    },
    onSelect(item) {
      if (!this.poiData.length || this.poiData[0].name !== item.name) {
        this.poiData.unshift(Object.assign({}, item));
        this.setPoiSelected(0);
      }
      if (item.location) {
        this.setMapCenter(item.location.lng, item.location.lat, this.chooseZoom);
      }
      this.chooseSuggestion = item;
    },
    onSuggestionBlur() {
      if (this.searchType === 0) {
        this.suggestionKeyWords = "";
      }
    },
    onDone() {
      const selected = this.poiData.find((d) => d.selected);
      if (!selected) {
        if (this.forceChoose) {
          this.$message.error(this.t("ele.map.message"));
          return;
        }
        this.doneLoading = true;
        this.getMapCenter(this.needCity).then((result) => {
          this.doneLoading = false;
          this.$emit("done", result);
        }).catch((e) => {
          console.error(e);
          this.doneLoading = false;
          this.$emit("done", {});
        });
        return;
      }
      const location = Object.assign({
        name: selected.name,
        address: selected.address || ""
      }, selected.location);
      if (this.needCity) {
        this.doneLoading = true;
        this.setMapCenter(location.lng, location.lat);
        this.getMapCenter(true).then(({ city }) => {
          this.doneLoading = false;
          location.city = city;
          this.$emit("done", location);
        }).catch((e) => {
          console.error(e);
          this.doneLoading = false;
          this.$emit("done", location);
        });
      } else {
        this.$emit("done", location);
      }
    },
    destroyAll() {
      this.destroyMap();
      this.poiData = [];
      this.suggestionData = [];
      this.suggestionKeywords = "";
      this.lastSuggestion = "";
      this.chooseSuggestion = null;
    },
    bounceIcon() {
      this.iconClass = [this.iconClass[0]];
      this.$nextTick(() => {
        setTimeout(() => {
          this.iconClass = [this.iconClass[0], "ele-map-picker-anim-bounce"];
        }, 0);
      });
    },
    setPoiSelected(index2) {
      this.poiData.forEach((d, i) => {
        d.selected = index2 === i;
      });
    },
    searchPoi(lng, lat, force) {
      if (!force && this.searchType !== 0) {
        this.poiLoading = false;
        return;
      }
      this.poiLoading = true;
      this.searchNearBy(lng, lat).then((data) => {
        this.poiLoading = false;
        if (this.chooseSuggestion) {
          if (data.length === 0 || data[0].name !== this.chooseSuggestion.name) {
            this.poiData = [
              Object.assign({ selected: true }, this.chooseSuggestion)
            ].concat(data);
          } else {
            this.poiData = data;
            this.poiData[0].selected = true;
          }
          this.chooseSuggestion = null;
        } else {
          this.poiData = data;
        }
      }).catch((e) => {
        this.poiLoading = false;
        console.error(e);
      });
    },
    renderMap() {
      var _a;
      if (!this.authenticated || this.map) {
        return;
      }
      const globalMapKey = (_a = this.$ELEADMIN) == null ? void 0 : _a.mapKey;
      AMapLoader__default["default"].load({
        key: this.mapKey || globalMapKey,
        version: this.mapVersion,
        plugins: ["AMap.PlaceSearch", "AMap.AutoComplete"]
      }).then((AMap) => {
        const option = {
          zoom: this.zoom,
          center: this.center,
          resizeEnable: true
        };
        if (this.mapStyle) {
          option.mapStyle = this.mapStyle;
        } else if (this.darkMode) {
          option.mapStyle = "amap://styles/dark";
        }
        this.map = new AMap.Map(this.$refs.mapEl, option);
        this.placeSearch = new AMap.PlaceSearch({
          type: this.poiType,
          pageSize: this.poiSize,
          pageIndex: 1
        });
        this.autoComplete = new AMap.AutoComplete({
          city: this.suggestionCity
        });
        this.centerMarker = new AMap.Marker({
          icon: new AMap.Icon({
            image: this.markerSrc,
            size: new AMap.Size(26, 36.5),
            imageSize: new AMap.Size(26, 36.5)
          }),
          offset: new AMap.Pixel(-13, -36.5)
        });
        this.map.on("complete", () => {
          const { lng, lat } = this.map.getCenter();
          this.loading = false;
          this.poiLoading = true;
          this.searchPoi(lng, lat, true);
        });
        this.map.on("moveend", () => {
          const { lng, lat } = this.map.getCenter();
          if (this.isSelMove) {
            this.isSelMove = false;
          } else {
            this.bounceIcon();
            this.searchPoi(lng, lat);
          }
        });
      }).catch((e) => {
        console.error(e);
      });
    },
    setMapCenter(lng, lat, zoom) {
      if (this.map) {
        if (typeof zoom === "undefined") {
          this.map.setCenter([lng, lat]);
        } else {
          this.map.setZoomAndCenter(zoom, [lng, lat]);
        }
      }
    },
    getMapCenter(needCity) {
      return new Promise((resolve, reject) => {
        if (!this.map) {
          reject(new Error("map is null"));
          return;
        }
        const result = this.map.getCenter();
        if (needCity) {
          this.map.getCity((city) => {
            result.city = city;
            resolve(result);
          });
        } else {
          resolve(result);
        }
      });
    },
    showCenterMarker(lng, lat) {
      if (!this.map) {
        console.error("map is null");
        return;
      }
      if (!this.centerMarker) {
        console.error("centerMarker is null");
        return;
      }
      if (typeof lng !== "undefined" && typeof lat !== "undefined") {
        this.centerMarker.setPosition([lng, lat]);
        this.map.add(this.centerMarker);
      } else {
        this.removeCenterMarker();
      }
    },
    removeCenterMarker() {
      if (this.map && this.centerMarker) {
        this.map.remove(this.centerMarker);
      }
    },
    searchNearBy(lng, lat) {
      return new Promise((resolve, reject) => {
        if (!this.placeSearch) {
          reject(new Error("placeSearch is null"));
          return;
        }
        this.placeSearch.searchNearBy(this.poiKeywords, [lng, lat], this.poiRadius, (status, result) => {
          if (status === "complete") {
            const data = result.poiList.pois.filter((p) => typeof p.location !== "undefined");
            resolve(data);
          } else {
            reject(new Error(status));
          }
        });
      });
    },
    searchKeywords(value) {
      return new Promise((resolve, reject) => {
        if (!this.autoComplete) {
          reject(new Error("autoComplete is null"));
          return;
        }
        this.autoComplete.search(value, (status, result) => {
          if (result.tips) {
            resolve(result.tips.map((d) => {
              return Object.assign({}, d, {
                text: d.name,
                value: d.name,
                address: Array.isArray(d.address) ? d.address[0] : d.address
              });
            }));
          } else {
            resolve([]);
          }
        });
      });
    },
    changeMapStyle(mapStyle, darkMode) {
      if (this.map) {
        if (mapStyle) {
          this.map.setMapStyle(mapStyle);
        } else if (darkMode) {
          this.map.setMapStyle("amap://styles/dark");
        } else {
          this.map.setMapStyle("amap://styles/normal");
        }
      }
    },
    destroyMap() {
      if (this.map) {
        this.map.destroy();
        this.placeSearch = null;
        this.autoComplete = null;
        this.centerMarker = null;
        this.map = null;
      }
    }
  },
  watch: {
    darkMode(value) {
      if (!this.mapStyle) {
        this.changeMapStyle(null, value);
      }
    },
    mapStyle(value) {
      if (value) {
        this.changeMapStyle(value);
      }
    }
  },
  unmounted() {
    this.destroyAll();
  }
};
const __cssModules = {};
var __component__ = /* @__PURE__ */ normalizeComponent(__vue2_script, render, staticRenderFns, false, __vue2_injectStyles, null, null, null);
function __vue2_injectStyles(context) {
  for (let o in __cssModules) {
    this[o] = __cssModules[o];
  }
}
var index = /* @__PURE__ */ function() {
  return __component__.exports;
}();
module.exports = index;
